package com.food.chain.db.realm;

import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.food.chain.dao.UserDao;

public class FoodChainRealm extends AuthorizingRealm {

	@Autowired
	private UserDao userDao;
	
	/**
	 * 授权，有三种方法会进入此方法
	 * 1.调用subject.hasRole(“admin”) 或 subject.isPermitted(“admin”)
	 * 2.@RequiresRoles("admin") ：在方法上加注解的时候；
	 * 3.在页面上加shiro标签的时候，即进这个页面的时候
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		// 授权信息
		SimpleAuthorizationInfo info = null;
		
		// 获取登录的用户ID
		// principalCollection.fromRealm(getName()).iterator().next();
		String userId = (String) getAvailablePrincipal(principalCollection);
		Map<String, Object> userInfo= userDao.getUserInfo(userId);
		if (userInfo != null && !userInfo.isEmpty()) {
			info = new SimpleAuthorizationInfo();
			// 用户的角色集合
			info.setRoles(userDao.getUserRoles(userId));
			// 设置用户的权限
			info.setStringPermissions(userDao.getPermissions(userId));
		}
		
		return info;
	}

	/**
	 * 认证
	 * 该方法在SecurityUtils.getSubject().login(token);的时候调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken aToken) throws AuthenticationException {
		SimpleAuthenticationInfo info = null;
		UsernamePasswordToken token = (UsernamePasswordToken) aToken;
		// 获取用户输入的用户ID
		String userId = token.getUsername();
		// 根据用户名到数据库查询数据获取指定的用户信息
		Map<String, Object> userInfo = userDao.getUserInfo(userId);
		if (userInfo != null && !userInfo.isEmpty()) {
			// 输入的password和数据库获得passWord对比
			// 相等才通过认证
			info = new SimpleAuthenticationInfo(userId, userInfo.get("U_Pwd"), this.getName());
		}
		
		return info;
	}
	
	/**
	 * 清除用户的权限缓存
	 */
	public void clearCacheAuth() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		this.clearCachedAuthenticationInfo(principals);
	}
	
	// 以下代码，要在更新角色后清除权限
	// 获取安全管理器
	//RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
	// 获取安全管理器中注入的自定义Realm
	//FoodChainRealm next = (FoodChainRealm) securityManager.getRealms().iterator().next();
	//next.clearCacheAuth();
}
